package com.selfdriving.activity;

import java.util.ArrayList;
import java.util.List;
import com.selfdriving.R;
import com.selfdriving.adapter.ContactAdapter;
import com.selfdriving.bean.Contact;
import com.selfdriving.dialog.FlippingLoadingDialog;
import com.selfdriving.dialog.MessageDialog;
import com.selfdriving.view.AlphabetListView;
import com.selfdriving.view.AlphabetListView.AlphabetPositionListener;

import android.database.Cursor;
import android.graphics.Path.FillType;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import net.tsz.afinal.annotation.view.ViewInject;

public class ContactActivity extends BaseActivity {
	@ViewInject(id = R.id.topBack, click = "topBack")
	ImageView topBack;

	@ViewInject(id = R.id.topText)
	TextView topText;

	@ViewInject(id = R.id.topRight)
	Button topRight;

	@ViewInject(id = R.id.list)
	AlphabetListView list;

	private List<Contact> contacts;

	private ContactAdapter adapter;

	private FlippingLoadingDialog loadingDialog;

	private Cursor cur;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		contacts = new ArrayList<Contact>();
		topText.setText("通讯录");
		topRight.setVisibility(View.GONE);
		loadingDialog = new FlippingLoadingDialog(this, "正在读取通讯录 请稍后");
		loadingDialog.show();
		new Thread(new Runnable() {
			@Override
			public void run() {
				getContact();
				mhandler.sendEmptyMessage(1);
			}
		}).start();
	}
	
	// 获得所有的联系人
	private void getContact(){
		cur = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				null,
				null,
				null,
				ContactsContract.Contacts.DISPLAY_NAME
						+ " COLLATE LOCALIZED ASC");

		// 循环遍历
		if (cur.moveToFirst()) {
			int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);

			int displayNameColumn = cur
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

			do {
				Contact contact = new Contact();
				// 获得联系人的ID号
				String contactId = cur.getString(idColumn);
				// 获得联系人姓名
				String disPlayName = cur.getString(displayNameColumn);
				contact.name = disPlayName;
				// 查看该联系人有多少个电话号码。如果没有这返回值为0
				int phoneCount = cur
						.getInt(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

				if (phoneCount > 0) {
					// 获得联系人的电话号码
					Cursor phones = getContentResolver().query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = " + contactId, null, null);
					if (phones.moveToFirst()) {
						do {
							// 遍历所有的电话号码
							String phoneNumber = phones
									.getString(phones
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
							contact.phone = phoneNumber;

							String phoneType = phones
									.getString(phones
											.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
						} while (phones.moveToNext());
					}
				}

				// 获取该联系人邮箱
				Cursor emails = getContentResolver().query(
						ContactsContract.CommonDataKinds.Email.CONTENT_URI,
						null,
						ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ " = " + contactId, null, null);
				if (emails.moveToFirst()) {
					do {
						// 遍历所有的电话号码
						String emailType = emails
								.getString(emails
										.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
						String emailValue = emails
								.getString(emails
										.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

					} while (emails.moveToNext());
				}

				// 获取该联系人IM
				Cursor IMs = getContentResolver().query(
						Data.CONTENT_URI,
						new String[] { Data._ID, Im.PROTOCOL, Im.DATA },
						Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
								+ Im.CONTENT_ITEM_TYPE + "'",
						new String[] { contactId }, null);
				if (IMs.moveToFirst()) {
					do {
						String protocol = IMs.getString(IMs
								.getColumnIndex(Im.PROTOCOL));
						String date = IMs
								.getString(IMs.getColumnIndex(Im.DATA));
					} while (IMs.moveToNext());
				}

				// 获取该联系人地址
				Cursor address = getContentResolver()
						.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
								null,
								ContactsContract.CommonDataKinds.Phone.CONTACT_ID
										+ " = " + contactId, null, null);
				if (address.moveToFirst()) {
					do {
						// 遍历所有的地址
						String street = address
								.getString(address
										.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
						String city = address
								.getString(address
										.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
						String region = address
								.getString(address
										.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
						String postCode = address
								.getString(address
										.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
						String formatAddress = address
								.getString(address
										.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
					} while (address.moveToNext());
				}

				// 获取该联系人组织
				Cursor organizations = getContentResolver().query(
						Data.CONTENT_URI,
						new String[] { Data._ID, Organization.COMPANY,
								Organization.TITLE },
						Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
								+ Organization.CONTENT_ITEM_TYPE + "'",
						new String[] { contactId }, null);
				if (organizations.moveToFirst()) {
					do {
						String company = organizations.getString(organizations
								.getColumnIndex(Organization.COMPANY));
						String title = organizations.getString(organizations
								.getColumnIndex(Organization.TITLE));
					} while (organizations.moveToNext());
				}

				// 获取备注信息
				Cursor notes = getContentResolver().query(
						Data.CONTENT_URI,
						new String[] { Data._ID, Note.NOTE },
						Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
								+ Note.CONTENT_ITEM_TYPE + "'",
						new String[] { contactId }, null);
				if (notes.moveToFirst()) {
					do {
						String noteinfo = notes.getString(notes
								.getColumnIndex(Note.NOTE));
					} while (notes.moveToNext());
				}

				// 获取nickname信息
				Cursor nicknames = getContentResolver().query(
						Data.CONTENT_URI,
						new String[] { Data._ID, Nickname.NAME },
						Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='"
								+ Nickname.CONTENT_ITEM_TYPE + "'",
						new String[] { contactId }, null);
				if (nicknames.moveToFirst()) {
					do {
						String nickname_ = nicknames.getString(nicknames
								.getColumnIndex(Nickname.NAME));
					} while (nicknames.moveToNext());
				}
				contacts.add(contact);
			} while (cur.moveToNext());
		}
	}

	public void topBack(View v) {
		this.finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (cur != null) {
			cur.close();
		}
	}
	
	private Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1: {
				adapter = new ContactAdapter(ContactActivity.this, contacts);
				 AlphabetPositionListener positionListener = new AlphabetPositionListener() {
				        @Override
				        public int getPosition(String letter) {
				            for(int i=0, count=contacts.size(); i<count; i++){
				                Character firstLetter = contacts.get(i).name.charAt(0);
				                if(firstLetter.toString().equals(letter)){
				                    return i;
				                }
				            }
				            return UNKNOW;
				        }
				    };
				list.setAdapter(adapter,positionListener);
				loadingDialog.dismiss();
				cur.close();
				break;
			}
			default: {
				if (msg.obj != null) {
					showToast((String) msg.obj);
				}
				break;
			}
			}
			super.handleMessage(msg);
		}
	};

}
